import tkinter as tk
from tkinter import messagebox
import csv
import os
import time

class Calculator:
    def __init__(self, master):
        self.master = master
        master.title("计算器")

        # create screen widget
        self.screen = tk.Entry(master, width=25, font=('Arial', 14))
        self.screen.grid(row=0, column=0, columnspan=4, padx=5, pady=5)

        # create buttons
        self.create_button('7', 1, 0)
        self.create_button('8', 1, 1)
        self.create_button('9', 1, 2)
        self.create_button('/', 1, 3)

        self.create_button('4', 2, 0)
        self.create_button('5', 2, 1)
        self.create_button('6', 2, 2)
        self.create_button('*', 2, 3)

        self.create_button('1', 3, 0)
        self.create_button('2', 3, 1)
        self.create_button('3', 3, 2)
        self.create_button('-', 3, 3)

        self.create_button('0', 4, 0)
        self.create_button('.', 4, 1)
        self.create_button('C', 4, 2)
        self.create_button('+', 4, 3)

        self.create_button('=', 5, 0, columnspan=4)

        # bind enter key to button click
        master.bind('<Return>', lambda event: self.button_click('='))

        # create menu bar
        menubar = tk.Menu(master)
        master.config(menu=menubar)

        # create file menu
        file_menu = tk.Menu(menubar, tearoff=0)
        #file_menu.add_command(label="历史记录", command=self.show_history)
        #file_menu.add_command(label="清除历史记录", command=self.clear_history)
        file_menu.add_command(label="退出", command=master.quit)
        menubar.add_cascade(label="文件", menu=file_menu)

        # create help menu
        help_menu = tk.Menu(menubar, tearoff=0)
        help_menu.add_command(label="关于", command=self.open_google)
        menubar.add_cascade(label="帮助", menu=help_menu)

    def create_button(self, text, row, column, columnspan=1):
        button = tk.Button(self.master, text=text, width=5, height=2, font=('Arial', 16),
                           command=lambda: self.button_click(text))
        button.grid(row=row, column=column, columnspan=columnspan, padx=5, pady=5)

    def button_click(self, text):
        if text == '=':
            try:
                result = eval(self.screen.get())
                self.screen.delete(0, tk.END)
                self.screen.insert(0, str(result))
                #with open('history.csv', mode='a', newline='') as history_file:
                #    history_writer = csv.writer(history_file)
                #    history_writer.writerow([self.screen.get(), str(result), time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())])
            except:
                self.screen.delete(0, tk.END)
                self.screen.insert(0, 'Error')
        elif text == 'C':
            self.screen.delete(0, tk.END)
        else:
            self.add_to_screen(text)

    def add_to_screen(self, text):
        if text.isdigit() or text in ['+', '-', '*', '/', '.', '(', ')']:
            self.screen.insert(tk.END, text)

    def show_history(self):
        if os.path.exists('history.csv'):
            with open('history.csv', mode='r') as history_file:
                history_reader = csv.reader(history_file)
                history_text = ""
                for row in history_reader:
                    history_text += row[0] + " = " + row[1]  + "  Time:"+row[2] + "\n"
                if history_text == "":
                    history_text = "没有找到历史记录"
                history_window = tk.Toplevel(self.master)
                history_window.title("历史记录")
                history_label = tk.Label(history_window, text=history_text, font=('Arial', 12))
                history_label.pack(padx=10, pady=10)
        else:
            print('No history found.')

    def clear_history(self):
        if os.path.exists('history.csv'):
            os.remove('history.csv')
            tk.messagebox.showinfo("提示", "历史记录已清除")
        else:
            tk.messagebox.showinfo("提示", "没有需要清除的历史记录")

    def open_google(self):
        import webbrowser
        webbrowser.open_new_tab("https://www.wdphp.com/?f=SoftCalculator")



root = tk.Tk()
calc = Calculator(root)
root.mainloop()